package reauthorize

import (
    "os"
	"strconv"
	"io/ioutil"
	//"dhfshop/utils/math"
	"dhfshop/models/member"
	"dhfshop/models/org"
	"dhfshop/controllers/base"
	"dhfshop/service/redisgo"
	"dhfshop/service/reauthorize"
	"github.com/astaxie/beego/validation"
	"github.com/pkg/errors"
	"github.com/astaxie/beego"
	"github.com/bitly/go-simplejson"
)


type TopTokenController struct {
	base.BaseController
}

/***********生成top token*******************/
func (this *TopTokenController) CreateTopToken() {
	rpcSecretCfg := beego.AppConfig.String("RpcSecret")
	v := struct {
		MemberId int64 `form:"member_id" valid:"Required"`
		Kinds    int   `form:"kinds"`
		//Desc    string  `form:"desc"      valid:"Required"`
	}{Kinds:0}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if curRoleId != 2{
		this.ServeError("cur login role is invalid")
		return
	}
	var memberId int64 = 0 
	if v.Kinds > 0 {
		value, err := org.GetUserByUserId(v.MemberId)
		if err != nil {
			err = errors.Wrap(err, "GetUserByUserId... ")
			this.ServeError(err.Error())
			return
		}
		memberId = value.UserId
	}else{
	    value, err := member.GetMemberById(v.MemberId)
		if err != nil {
			err = errors.Wrap(err, "GetMemberById... ")
			this.ServeError(err.Error())
			return
		}
	    memberId = value.MemberId
	}
	signer := reauthorize.NewSigner("dhf",100, rpcSecretCfg)
	signerUser := reauthorize.User{PartnerId:partnerId,MemberId:memberId,Scenes:"TopAuth"}
	token, err := signer.Sign(signerUser)
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	//beego.Debug(token)
	redisconn := redisgo.GetInstance()
	partnerIdStr := strconv.FormatInt(partnerId, 10)
	memberIdStr := strconv.FormatInt(memberId, 10)
	cacheKey := "toptoken_" + partnerIdStr + "_" + memberIdStr
	if ok, _:= redisconn.Exists(cacheKey); ok {
		redisconn.Del(cacheKey)  //
	}
	_, err = redisconn.Set(cacheKey, token, 3*24*3600)
	if err != nil {
	   //beego.Debug("SETEX", err.Error())
	   this.ServeError(err.Error())
	   return
	}
	this.ServeOk("success")
	return
}

func InitTopUrl(urlFileName string) (err error) {
	file, err := os.Open(urlFileName)
	if err != nil {
		return err
	}
	defer file.Close()
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}
	js, err := simplejson.NewJson(content)
	if err!=nil {
		return err
	}
	items, err := js.Get("urls").Array()
	if err!=nil {
		return err
	}
	base.MapTopAuthUrl = make(map[string]string)
	for i := 0; i < len(items); i++ {
		name, _:= js.Get("urls").GetIndex(i).Get("name").String()
		identity, _:= js.Get("urls").GetIndex(i).Get("identity").String()
		base.MapTopAuthUrl[identity] = name
	}
    return nil 
}
